#include "wsi_map_connectid.h"

// 全局连接映射表
ConnectionMap *connection_map = NULL;

// 生成唯一连接 ID
void generate_connection_id(char *buffer, size_t size) {
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    if (size) {
        --size;
        for (size_t n = 0; n < size; n++) {
            int index = rand() % (int)(sizeof charset - 1);
            buffer[n] = charset[index];
        }
        buffer[size] = '\0';
    }
}

// 添加连接到映射表
void add_connection_to_map(const char *connection_id, struct lws *wsi) {
    ConnectionMap *entry = malloc(sizeof(ConnectionMap));
    strncpy(entry->connection_id, connection_id, sizeof(entry->connection_id) - 1);
    entry->connection_id[sizeof(entry->connection_id) - 1] = '\0';
    entry->wsi = wsi;
    HASH_ADD_STR(connection_map, connection_id, entry);
}

// 从映射表移除连接
void remove_connection_from_map(const char *connection_id) {
    ConnectionMap *entry = NULL;
    HASH_FIND_STR(connection_map, connection_id, entry);
    if (entry) {
        HASH_DEL(connection_map, entry);
        free(entry);
    }
}

// 通过连接 ID 获取 wsi
struct lws *get_wsi_by_connection_id(const char *connection_id) {
    ConnectionMap *entry = NULL;
    HASH_FIND_STR(connection_map, connection_id, entry);
    return entry ? entry->wsi : NULL;
}